<?php

namespace framework\support;

use framework\third_party\Medoo;
use PDO;




class Db
{
    private static $_instance = null;
    private static  $database = null;
    /**
     * Single constructor. 私有的构造方法
     */
    private function __construct()
    {;
    }

    /**
     * @purpose: 创建__clone方法防止对象被复制克隆
     */
    private function __clone()
    {
        // E_USER_ERROR只能通过trigger_error($msg, E_USER_ERROR)手动触发。
        // E_USER_ERROR是用户自定义错误类型，可以被set_error_handler错误处理函数捕获，允许程序继续运行。
        // E_ERROR是系统错误，不能被set_error_handler错误处理函数捕获，程序会退出运行
        trigger_error('Clone is not allow!', E_USER_ERROR);
    }


    /**
     * @return Single|Object 单例方法,用于访问实例的公共的静态方法
     */
    public static function getInstance()
    {
        if (!self::$_instance) {
            self::$_instance = new self;
            $host = $_ENV['DB_HOST'] ?? null;
            $port = $_ENV['DB_PORT'] ?? '3306';
            $name = $_ENV['DB_NAME'];
            $charset = $_ENV['DB_CHARSET'] ?? 'utf8';
            $user = $_ENV['DB_USER'] ?? 'root';
            $prefix = $_ENV['DB_PREFIX'] ?? '';
            $password = $_ENV['DB_PASSWORD'] ?? '';
            $driver = $_ENV['DB_DRIVER'] ?? 'mysql';
            if ($host) {
                try {
                    self::$database = new Medoo([
                        // required
                        'database_type' => $driver,
                        'database_name' => $name,
                        'server' => $host,
                        'username' => $user,
                        'password' => $password,

                        // [optional]
                        'charset' => $charset,
                        'port' => $port,

                        // [optional] Table prefix
                        'prefix' => $prefix,

                        // [optional] driver_option for connection, read more from http://www.php.net/manual/en/pdo.setattribute.php
                        'option' => [
                            PDO::ATTR_CASE => PDO::CASE_NATURAL
                        ],
                        // [optional] Medoo will execute those commands after connected to the database for initialization
                        'command' => [
                            'SET SQL_MODE=ANSI_QUOTES'
                        ]
                    ]);
                } catch (\Exception $e) {
                    echo $e->getMessage();
                    return throw new \Exception("数据库连接失败");
                }
            }
        }
        return self::$_instance;
    }

    public static function getDatabase()
    {
        return self::$database;
    }



    //当请求不存在的方法时执行
    public static function __callStatic($name, $arguments)
    {
        if (method_exists(self::$database, $name)) {
            return self::$database->$name(...$arguments);
        } else {
            return throw new \Exception("Method {$name} not found");
        }
    }
}
